<?php
/**
  * //w/w/w.s/h/u/o/t//u/p/u c/o/m  说 图/谱/源/码/分/享
 */
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/12 0012
 * Time: 16:50
 * 畜牧领养
 */
defined("IN_IA")or exit("Access denied");
global $_GPC,$_W;
$uniacid=$_GPC['uniacid'];
$op=$_GPC['op'] ? $_GPC['op'] :"index";
$uid=$_GPC['uid'];
//畜牧领养（获取全部可领养畜牧的数据）
if($op=='index'){
	$request=array();
	$animalData=pdo_getall('cqkundian_farm_animal',array('uniacid'=>$uniacid,'is_putaway'=>1),'','','rank asc');
	$request['animalData']=$animalData;
	echo json_encode($request);
}

//畜牧详情页获取数据
if($op=='animalDetail'){
	$request=array();
	$aid=$_GPC['aid'];
	$animalData=pdo_get('cqkundian_farm_animal',array('uniacid'=>$uniacid,'id'=>$aid));
	$animalData['animal_slide']=unserialize($animalData['animal_slide']);
	//商品规格
	if($animalData['is_open_sku']==1){
		$animalSpecItem=pdo_getall('cqkundian_farm_animal_spec',array('aid'=>$aid,'uniacid'=>$uniacid));
		for($i=0;$i<count($animalSpecItem);$i++){
			$animalSpecItem[$i]['specVal']=pdo_getall('cqkundian_farm_animal_spec_value',array('uniacid'=>$uniacid,'spec_id'=>$animalSpecItem[$i]['id']));
		}
		$request['animalSpecItem']=$animalSpecItem;
	}
	echo json_encode($request);die;
}
//获取家畜详情页
if($op=='getAnimalDetailData'){
    $request=array();
    $aid=$_GPC['aid'];
    $animalData=pdo_get('cqkundian_farm_animal',array('id'=>$aid,'uniacid'=>$uniacid));
    $animalData['animal_slide']=unserialize($animalData['animal_slide']);   //反序列化轮播图片
    $animalData['animal_rule']=unserialize($animalData['animal_rule']);
    $animalData['adopt_desc']=explode("\n",$animalData['adopt_desc']);
    //查询家畜规格
    $animalSpecItem=pdo_getall('cqkundian_farm_animal_spec',array('aid'=>$aid,'uniacid'=>$uniacid));
    for($i=0;$i<count($animalSpecItem);$i++){
        $animalSpecVal=pdo_getall('cqkundian_farm_animal_spec_value',array('spec_id'=>$animalSpecItem[$i]['id'],'uniacid'=>$uniacid));
        for($j=0;$j<count($animalSpecVal);$j++){
            $animalSpecVal[$j]['is_select']=0;  //未选择
        }
        $animalSpecItem[$i]['specVal']=$animalSpecVal;
        $animalSpecItem[$i]['is_select']=0;     //未选择
    }
    $request['animalData']=$animalData;
    $request['animalSpecItem']=$animalSpecItem;
    //关于我们
    $aboutData=pdo_get('cqkundian_farm_about',array('uniacid'=>$uniacid));
    $request['aboutData']=$aboutData;
    echo json_encode($request);die;
}

//获取家畜规格信息
if($op=='getAnimalSpec'){
    $aid=$_GPC['aid'];
    $spec_id_str=$_GPC['spec_id'];
    $spec_id_arr=explode(",", $spec_id_str);
    sort($spec_id_arr);
    $animalData=pdo_get('cqkundian_farm_animal',array('id'=>$aid,'uniacid'=>$uniacid));
    $specItem=pdo_getall('cqkundian_farm_animal_spec_value',array('id in'=>$spec_id_arr));
    $sku_name_arr=array();
    for($i=0;$i<count($specItem);$i++){
        $sku_name_arr[]=$specItem[$i]['spec_value'];
    }
    $sku_name_str=implode('+',$sku_name_arr);
    $sku_name=implode(',', $spec_id_arr);
    $specVal=pdo_get('cqkundian_farm_animal_sku',array('sku_name'=>$sku_name,'aid'=>$aid,'uniacid'=>$uniacid));
    if($specVal){       //存在该规格
        //判断该规格的库存是否大于0
        if($specVal['spec_src']==''){
            $specVal['spec_src']=$animalData['animal_src'];
        }
        if($specVal['count']>=1){
            $request['code']=1;
        }else{
            $request['code']=2; //库存不足
        }
        $request['specVal']=$specVal;
    }else{
        $request['code']=3;
    }
    $request['sku_name_str']=$sku_name_str;
    echo json_encode($request);die;
}

//确认领养
if($op=='sureAdoptAnimal'){
    $aid=$_GPC['aid'];
    $count=$_GPC['count'];

    $coupon_id=$_GPC['coupon_id'];
    $coupon_price=$_GPC['coupon_price'];
    $username=$_GPC['username'];
    $phone=$_GPC['phone'];
    $animalData=pdo_get('cqkundian_farm_animal',array('id'=>$aid,'uniacid'=>$uniacid));
    include 'function.inc.php';
    $farmSetData=getFarmSetData(array('is_open_distribution','distribution_one_price','distribution_two_price'),array('uniacid'=>$uniacid));
    if(!empty($_GPC['spec_id']) && $_GPC['spec_id']!=undefined){       //存在规格值
        $spec_id=$_GPC['spec_id'];
        $insertData=array(
            'order_number'=>rand(100,999).time().rand(100,999),
            'aid'=>$aid,
            'count'=>$count,
            'create_time'=>time(),
            'uniacid'=>$uniacid,
            'spec_id'=>$spec_id,
            'status'=>0,        //未支付
            'uid'=>$uid,
            'body'=>'领养'.$animalData['animal_name'],
            'coupon_id'=>$coupon_id,
            'coupon_price'=>$coupon_price,
            'username'=>$username,
            'phone'=>$phone,
        );
        //计算总价
        $specVal=pdo_get('cqkundian_farm_animal_sku',array('id'=>$spec_id,'uniacid'=>$uniacid));
        $total_price=$specVal['price']*$count;
        if($coupon_id && $coupon_price){
            $total_price=$total_price-$coupon_price;  //优惠券抵用
        }
        $insertData['total_price']=$total_price;
    }else{  //不存在规格
        $insertData=array(
            'order_number'=>rand(100,999).time().rand(100,999),
            'aid'=>$aid,
            'count'=>$count,
            'create_time'=>time(),
            'uniacid'=>$uniacid,
            'spec_id'=>0,
            'status'=>0,        //未支付
            'uid'=>$uid,
            'body'=>'领养'.$animalData['animal_name'],
            'coupon_id'=>$coupon_id,
            'coupon_price'=>$coupon_price,
            'username'=>$username,
            'phone'=>$phone,
        );
        //计算总价
        $total_price=$animalData['price']*$count;
        if($coupon_id && $coupon_price){
            $total_price=$total_price-$coupon_price;  //优惠券抵用
        }
        $insertData['total_price']=$total_price;
    }

    //是否开启分销
    if($farmSetData['is_open_distribution']==1){
        $user=pdo_get('cqkundian_farm_user',array('uniacid'=>$uniacid,'uid'=>$uid));
        //当前下单用户的一级分销商
        if($user['one_distributor']!=0) {
            $insertData['is_price']=1;
            $one_sale = pdo_get('cqkundian_farm_user', array('uniacid' => $uniacid, 'uid' => $user['one_distributor']));
            $insertData['one_price']=round($insertData['total_price']*($farmSetData['distribution_one_price']/100),2);
            if($one_sale['one_distributor']!=0){
                $insertData['two_price']=round($insertData['total_price']*($farmSetData['distribution_two_price']/100),2);
            }
        }
    }

    $animal_order_res=pdo_insert('cqkundian_farm_animal_order',$insertData);
    $order_id=pdo_insertid();
    if($animal_order_res){
        if($coupon_id && $coupon_price){
            //修改优惠券使用
            pdo_update('cqkundian_farm_user_coupon',array('status'=>1),array('uniacid'=>$uniacid,'uid'=>$uid,'cid'=>$coupon_id));
        }
        echo json_encode(array('code'=>1,'order_id'=>$order_id));die;
    }else{
        echo json_encode(array('code'=>2));die;
    }
}

//微信支付回调
if($op=='notify'){
    $order_id=$_GPC['order_id'];
    $prepay_id_str=$_GPC['prepay_id'];
    $orderData=pdo_get('cqkundian_farm_animal_order',array('id'=>$order_id,'uniacid'=>$uniacid));
    if($orderData['status']==1) {
        include 'function.inc.php';
        if($orderData['is_price']==1){
            saleSendPirce($orderData,$uniacid,3);
            pdo_update('cqkundian_farm_animal_order',array('is_price'=>2),array('uniacid'=>$uniacid,'id'=>$order_id));
        }
        //更新商品的销量
        updateSaleCount($order_id, $uniacid);
        //更新商品库存
        updateGoodsCount($order_id, $uniacid);
        adoptAnimal($order_id, $uniacid);
        //向用户推送消息
        $prepay_id = explode('=', $prepay_id_str);
        $wxData = pdo_get('cqkundian_farm_wx_set', array('uniacid' => $uniacid));
        $page = '/kundian_farm/pages/user/Animal/index';
        $res_user_send = send_msg_to_user($orderData, $prepay_id[1], $_W['openid'], $uniacid, $page);
        //给店家推送消息
        $wx_openid = unserialize($wxData['get_openid']);
        for ($i = 0; $i < count($wx_openid); $i++) {
            $res_send_shop = send_other_template_message($wx_openid[$i], $orderData, $uniacid);
        }
        echo json_encode(array('code' => 1));
        die;
    }else{
        echo json_encode(array('code' => 2));
        die;
    }
}

//获取我喂养的家畜
if($op=='getMyAnimal'){
    $request=array();
    $status=$_GPC['status'];
    $condition=array(
        'uid'=>$uid,
        'uniacid'=>$uniacid,
    );
    if($status==1){
        $condition['status']=array(2,4);
    }elseif ($status==2){
        $condition['status']=1;
    }elseif ($status==3){
        $condition['status']=5;
    }
    $page=empty($_GPC['page']) ? 1:intval($_GPC['page'])+1;
    $animalData=pdo_getall('cqkundian_farm_animal_adopt',$condition,'','','create_time desc',array($page,10));
    $begin_time=strtotime(date('Y-m-d',time()));
    for($i=0;$i<count($animalData);$i++){
        $detail=pdo_get('cqkundian_farm_animal',array('id'=>$animalData[$i]['aid'],'uniacid'=>$uniacid));
        $animalData[$i]['animal_src']=$detail['animal_src'];
        $animalData[$i]['animal_name']=$detail['animal_name'];
        $animalData[$i]['animal_type']=$detail['animal_type'];
        $animalData[$i]['predict_ripe']=date("Y/m/d",$animalData[$i]['predict_ripe']);
        //更新领养天数
        $day=floor((time()-$animalData[$i]['today_time'])/60/60/24);
        pdo_update('cqkundian_farm_animal_adopt',array('adopt_day'=>$day),array('id'=>$animalData[$i]['id'],'uniacid'=>$uniacid,'status'=>array(2,4)));
    }
    $request['animalData']=$animalData;
    echo json_encode($request);die;
}

//我的家畜详情
if($op=='getAdoptDetail'){
    $request=array();
    $adopt_id=$_GPC['adopt_id'];
    $adoptData=pdo_get('cqkundian_farm_animal_adopt',array('id'=>$adopt_id,'uniacid'=>$uniacid));
    $animalData=pdo_get('cqkundian_farm_animal',array('id'=>$adoptData['aid'],'uniacid'=>$uniacid));
    $animalData['animal_slide']=unserialize($animalData['animal_slide']);
    $request['adoptData']=$adoptData;
    $request['animalData']=$animalData;
    //判断当前的进度
    $between=$adoptData['predict_ripe']-$adoptData['create_time'];
    $between_day=floatval($adoptData['adopt_day']/(intval($between/60/60/24)));
    $request['between_day']=intval($between_day*100);
    $request['between_day_day']=intval($between/60/60/24);
    //查询家畜状态跟踪
    $statusData=pdo_getall('cqkundian_farm_animal_adopt_status',array('adopt_id'=>$adopt_id,'uniacid'=>$uniacid),'','','create_time desc',array(1,10));
    for($i=0;$i<count($statusData);$i++){
        $statusData[$i]['create_time']=date("Y-m-d H:i",$statusData[$i]['create_time']);
        $statusData[$i]['src']=unserialize($statusData[$i]['src']);
    }
    $request['statusData']=$statusData;
    echo json_encode($request);die;
}

//获取更多的跟踪信息
if($op=='getStatusData'){
    $request=array();
    $page=empty($_GPC['page']) ? 1:intval($_GPC['page'])+1;
    $adopt_id=$_GPC['adopt_id'];
    $statusData=pdo_getall('cqkundian_farm_animal_adopt_status',array('adopt_id'=>$adopt_id,'uniacid'=>$uniacid),'','','create_time desc',array($page,10));
    for($i=0;$i<count($statusData);$i++){
        $statusData[$i]['create_time']=date("Y-m-d H:i",$statusData[$i]['create_time']);
        $statusData[$i]['src']=unserialize($statusData[$i]['src']);
    }
    $request['statusData']=$statusData;
    echo json_encode($request);die;
}

//宰杀并寄送
if($op=='getSureOrder'){
    $request=array();
    $adopt_id=$_GPC['adopt_id'];
    $adoptData=pdo_get('cqkundian_farm_animal_adopt',array('id'=>$adopt_id,'uniacid'=>$uniacid));
    $aboutData=pdo_get('cqkundian_farm_about',array('uniacid'=>$uniacid));
    $orderData=pdo_get('cqkundian_farm_animal_order',array('id'=>$adoptData['order_id']));
    $animalData=pdo_get('cqkundian_farm_animal',array('id'=>$adoptData['aid'],'uniacid'=>$uniacid));
    $specVal=pdo_get('cqkundian_farm_animal_sku',array('id'=>$orderData['spec_id'],'uniacid'=>$uniacid));
    $spec_id=explode(",", $specVal['sku_name']);
    $spec_val=pdo_getall('cqkundian_farm_animal_spec_value',array('id in'=>$spec_id));
    $specItem=pdo_getall('cqkundian_farm_animal_spec',array('aid'=>$orderData['aid'],'uniacid'=>$uniacid));
    for($j=0;$j<count($specItem);$j++){
        for($m=0;$m<count($spec_val);$m++){
            if($specItem[$j]['id']==$spec_val[$m]['spec_id']){
                $specItem[$j]['spec_value']=$spec_val[$m]['spec_value'];
            }
        }
    }
    $request['adoptData']=$adoptData;
    $request['animalData']=$animalData;
    $request['specItem']=$specItem;
    $request['aboutData']=$aboutData;
    echo json_encode($request);die;
}

//生成订单
if($op=='addOrder'){
    $name=$_GPC['name'];
    $address=$_GPC['address'];
    $phone=$_GPC['phone'];
    $adopt_id=$_GPC['adopt_id'];
    $aboutData=pdo_get('cqkundian_farm_about',array('uniacid'=>$uniacid));
    $adoptData=pdo_get('cqkundian_farm_animal_adopt',array('id'=>$adopt_id,'uniacid'=>$uniacid));
    $orderData=pdo_get('cqkundian_farm_animal_order',array('id'=>$adoptData['order_id']));
    $animalData=pdo_get('cqkundian_farm_animal',array('id'=>$adoptData['aid'],'uniacid'=>$uniacid));
    $insertData=array(
        'order_number'=>rand(100,999).time().rand(100,999),
        'uid'=>$uid,
        'status'=>0,
        'create_time'=>time(),
        'name'=>$name,
        'address'=>$address,
        'phone'=>$phone,
        'uniacid'=>$uniacid,
        'send_price'=>$aboutData['send_price'],
        'total_price'=>$aboutData['send_price'],    //只需要支付运费
        'order_type'=>3,
        'body'=>$animalData['animal_name'].'宰杀',
    );
    $order_res=pdo_insert('cqkundian_farm_shop_order',$insertData);
    $order_id=pdo_insertid();
    $insertDetail=array(
        'goods_id'=>$animalData['id'],
        'order_id'=>$order_id,
        'goods_name'=>$animalData['animal_name'],
        'cover'=>$animalData['animal_src'],
        'price'=>$animalData['price'],
        'count'=>1,
        'spec_id'=>$orderData['spec_id'],
        'uniacid'=>$uniacid,
    );
    $detail_res=pdo_insert('cqkundian_farm_shop_order_detail',$insertDetail);
    if($order_res && $detail_res){
        echo json_encode(array('code'=>1,'order_id'=>$order_id));die;
    }else{
        echo json_encode(array('code'=>2));die;
    }
}

if($op=='notify_send'){
    $adopt_id=$_GPC['adopt_id'];
    $order_id=$_GPC['order_id'];
    $prepay_id_str=$_GPC['prepay_id'];
    $orderData=pdo_get('cqkundian_farm_shop_order',array('id'=>$order_id,'uniacid'=>$uniacid));
    if($orderData['status']==1) {
        $update_animal = pdo_update('cqkundian_farm_animal_adopt', array('status' => 5), array('id' => $adopt_id, 'uniacid' => $uniacid));
        insertIntegral($uniacid, $order_id);
        //向用户推送消息
        $prepay_id = explode('=', $prepay_id_str);
        $wxData = pdo_get('cqkundian_farm_wx_set', array('uniacid' => $uniacid));
        include 'function.inc.php';
        $page = '/kundian_farm/pages/shop/orderList/index';
        $res_user_send = send_msg_to_user($orderData, $prepay_id[1], $_W['openid'], $uniacid, $page);
        //给店家推送消息
        $wx_openid = unserialize($wxData['get_openid']);
        for ($i = 0; $i < count($wx_openid); $i++) {
            $res_send_shop = send_template_message($wx_openid[$i], $orderData, $uniacid);
        }
        echo json_encode(array('code' => 1));
        die;
    }else{
        echo json_encode(array('code' => 2));
        die;
    }
}

/**
 * 更新家畜销量
 * @param $order_id
 * @param $uniacid
 */
function updateSaleCount($order_id,$uniacid){
    $orderData=pdo_get('cqkundian_farm_animal_order',array('id'=>$order_id,'uniacid'=>$uniacid));
    $goods_where=array(
        'id'=>$orderData['aid'],
        'uniacid'=>$uniacid,
    );
    pdo_update('cqkundian_farm_animal',array('sale_count +='=>$orderData['count']),$goods_where);
}

/**
 * 更新库存
 * @param $order_id
 * @param $uniacid
 */
function updateGoodsCount($order_id,$uniacid){
    $orderData=pdo_get('cqkundian_farm_animal_order',array('id'=>$order_id,'uniacid'=>$uniacid));
    $specVal=pdo_get('cqkundian_farm_animal_sku',array('id'=>$orderData['spec_id']));
    if($orderData['spec_id']!=0){
        pdo_update('cqkundian_farm_animal_sku',array('count -='=>$orderData['count']),array('id'=>$orderData['spec_id'],'uniacid'=>$uniacid));
    }else{
        pdo_update('cqkundian_farm_animal',array('count -='=>$orderData['count']),array('id'=>$orderData['aid'],'uniacid'=>$uniacid));
    }
}

/**
 * 插入领养信息
 * @param $order_id
 * @param $uniacid
 */
function adoptAnimal($order_id,$uniacid){
    $orderData=pdo_get('cqkundian_farm_animal_order',array('id'=>$order_id,'uniacid'=>$uniacid));
    //查询是否已经插入了领养信息，防止重复插入
    $is_have=pdo_get('cqkundian_farm_animal_adopt',array('uniacid'=>$uniacid,'id','order_id'=>$order_id));
    if(empty($is_have)) {
        $animalData = pdo_get('cqkundian_farm_animal', array('id' => $orderData['aid'], 'uniacid' => $uniacid));
        for ($i = 0; $i < $orderData['count']; $i++) {
            $insertAdopt = array(
                'uid' => $orderData['uid'],
                'aid' => $orderData['aid'],
                'create_time' => time(),
                'status' => 1,
                'adopt_day' => 0,
                'predict_ripe' => $animalData['mature_period'] * 24 * 60 * 60 + time(),     //预计成熟期
                'uniacid' => $uniacid,
                'order_id' => $order_id,
            );
            pdo_insert('cqkundian_farm_animal_adopt', $insertAdopt);
        }
    }
}

/**
 * 添加积分记录
 * @param $uniacid
 * @param $uid
 * @param $score
 */
function insertIntegral($uniacid,$order_id){
    $orderData=pdo_get('cqkundian_farm_animal_order',array('id'=>$order_id,'uniacid'=>$uniacid));
    $aboutData=pdo_get('cqkundian_farm_about',array('uniacid'=>$uniacid));
    $userData=pdo_get('cqkundian_farm_user',array('uid'=>$orderData['uid'],'uniacid'=>$uniacid));
    $score=round($orderData['total_price']/$aboutData['pay_integral']);
    pdo_update('cqkundian_farm_user',array('score +='=>$score),array('uid'=>$orderData['uid'],'uniacid'=>$uniacid));
    $insertData=array(
        'uid'=>$orderData['uid'],
        'uniacid'=>$uniacid,
        'create_time'=>time(),
        'score_type'=>1,
        'score'=>$score,
        'body'=>$orderData['body'],
        'now_score'=>$userData['score']+$score,
    );
    pdo_insert('cqkundian_farm_integral_record',$insertData);
}

